<?php

namespace apiend\modules\passport\controllers;

use Yii;
use apiend\components\Controller;
use apiend\modules\passport\models\RegisterForm;
use common\helpers\ArrayHelper;

/**
 * 短信登录/注册
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class RegisterController extends Controller {

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
        ];
    }

    /**
     * 用户注册
     * @inheritdoc
     */
    public function actionIndex() {
        $model = new RegisterForm();
        $params = Yii::$app->request->post();
        $ms = ArrayHelper::remove($params, 'ms');
        if ($ms) {
            /* @var $security \common\base\Security */
            $security = Yii::$app->security;
            foreach ($params as $k => $v) {
                if ($k == 'code' && strlen($v) == 6) {
                    continue;
                }
                $params[$k] = $security->decryptDataByKey($v);
            }
        }
        if (!$model->load($params, '')) {
            parent::error('请输入手机号和短信验证码');
        }
        return $model->register();
    }

    /**
     * {@inheritdoc}
     */
    public function afterAction($action, $result) {
        if (!$this->token->bindUser($result->id)) {
            parent::error('登录失败', $this->token->firstErrors);
        }
        return parent::afterAction($action, $result);
    }

}
